//
//  PayLayer.m
//  Pay
//
//  Created by steve on 15-1-6.
//  Copyright (c) 2015年 steve. All rights reserved.
//

#import "PayLayer.h"

#define ANIMATIONDURATION 3
#define PULSEINTERVAL 0

@interface WaveLayer : CALayer

- (void) push ;

@end

@implementation WaveLayer

- (instancetype)init
{
  self = [super init];
  if (self) {
    self.cornerRadius = WAVE_RADIUS;
    self.backgroundColor = [[UIColor colorWithRed:1.F
                                            green:0.55F
                                             blue:0.F
                                            alpha:1.F] CGColor];
    self.opacity = 0.F;
  }
  return self;
}

- (CAAnimationGroup *)setupAnimationGroup {
  
  CAMediaTimingFunction *defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
  
  CAAnimationGroup *ag = [CAAnimationGroup animation];
  ag.duration = ANIMATIONDURATION + PULSEINTERVAL;
  ag.removedOnCompletion = NO;
  ag.timingFunction = defaultCurve;
  
  CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
  scaleAnimation.fromValue = @0.0;
  scaleAnimation.toValue = @1.0;
  scaleAnimation.duration = ANIMATIONDURATION;
  
  CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
  opacityAnimation.duration = ANIMATIONDURATION;
  opacityAnimation.values = @[@0.45, @0.45, @0];
  opacityAnimation.keyTimes = @[@0, @0.2, @1];
  opacityAnimation.removedOnCompletion = NO;
  
  ag.animations = @[scaleAnimation, opacityAnimation];
  
  return ag;
}

- (void) push {
  [self addAnimation:[self setupAnimationGroup] forKey:@"push"];
}

@end

#pragma mark - ProgressLayer -

@interface ProgressLayer : CALayer

@property (nonatomic, strong) CAShapeLayer *arcLayer;

- (void) play ;

- (void) stop ;

@end

@implementation ProgressLayer

- (instancetype)init
{
  self = [super init];
  if (self) {
    [self intiUIOfView];
  }
  return self;
}

-(void)drawLineAnimation:(CALayer*)layer
{
  CABasicAnimation *bas=[CABasicAnimation animationWithKeyPath:@"strokeStart"];
    NSInteger time = 10;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"progressDuration"]) {
        time = [[[NSUserDefaults standardUserDefaults] objectForKey:@"progressDuration"] integerValue];
    }
  bas.duration=time;
  bas.delegate=self;
  bas.fromValue=[NSNumber numberWithInteger:1];
  bas.toValue=[NSNumber numberWithInteger:0];
  bas.repeatCount = INFINITY;
  [layer addAnimation:bas forKey:@"key"];
}

-(void)intiUIOfView
{
  CGRect rect = CGRectMake(0, 0, WAVE_RADIUS * 2, WAVE_RADIUS * 2);
  UIBezierPath *path = [UIBezierPath bezierPath];
  [path addArcWithCenter:CGPointMake(rect.size.width * 0.5F, rect.size.height * 0.5F)
                  radius:WAVE_RADIUS * 0.25F
              startAngle:0
                endAngle:2 * M_PI
               clockwise:NO];
  
  _arcLayer = [CAShapeLayer layer];
  _arcLayer.path = path.CGPath;//46,169,230
  _arcLayer.fillColor = [[UIColor clearColor] CGColor];
  _arcLayer.strokeColor = [[UIColor colorWithWhite:1 alpha:0] CGColor];
  _arcLayer.lineWidth = 3;
  _arcLayer.frame = CGRectMake(0, 0, 50, 50);
  [self addSublayer:_arcLayer];
}

- (void) play {
  if ([_arcLayer animationForKey:@"key"])
    return ;
  
  _arcLayer.strokeColor = [[UIColor colorWithWhite:1 alpha:0.9] CGColor];
  [self drawLineAnimation:_arcLayer];
}

- (void) stop {
  [_arcLayer removeAnimationForKey:@"key"];
  _arcLayer.strokeColor = [[UIColor colorWithWhite:1 alpha:0] CGColor];
}

@end

#pragma mark - PayLayer -

@interface PayLayer()

@property (strong, nonatomic) NSMutableArray *waves;
@property (assign, nonatomic) NSUInteger index;
@property (assign, atomic) BOOL playing;
@property (strong, nonatomic) ProgressLayer *progress;

@end

@implementation PayLayer

- (instancetype)init
{
  self = [super init];
  if (self) {
    _waves = [NSMutableArray arrayWithCapacity:10];
    _index = 0;
    _playing = NO;
    
    // 声波圈
    for (NSUInteger i = 0; i < 4; i++) {
      WaveLayer *p = [[WaveLayer alloc] init];
      p.frame = CGRectMake(0, 0, WAVE_RADIUS * 2, WAVE_RADIUS * 2);
      [self addSublayer:p];
      [_waves addObject:p];
    }
    
    // 遮挡1
    CAShapeLayer *shapeBorder = [self shapeWithRadius:WAVE_RADIUS * 0.4F
                                          frame:CGRectMake(0, 0, WAVE_RADIUS * 0.5F, WAVE_RADIUS * 0.5F)
                                      fillColor:[UIColor colorWithRed:0.95686275F
                                                                green:0.81176471F
                                                                 blue:0.62745098F
                                                                alpha:1.F]];
    [self addSublayer:shapeBorder];
    
    // 遮挡2
    CAShapeLayer *shape = [self shapeWithRadius:WAVE_RADIUS * 0.255F
                                          frame:CGRectMake(0, 0, WAVE_RADIUS * 0.5F, WAVE_RADIUS * 0.5F)
                                      fillColor:[UIColor colorWithRed:1.F
                                                                green:0.55F
                                                                 blue:0.F
                                                                alpha:1.F]];
    [self addSublayer:shape];
    
    // 进度
    _progress = [[ProgressLayer alloc] init];
    [self addSublayer:_progress];
    
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, WAVE_RADIUS * 2, WAVE_RADIUS * 2);
  }
  return self;
}

- (void) play {
  _playing = YES;
  [self go:^{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      if (_playing)
        [self play];
    });
  }];
  [_progress play];
}

- (void) playOnce {
  _playing = YES;
  [self go:^{
    
  }];
  [_progress play];
}

- (void) stop {
  _playing = NO;
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(go:)
                                             object:nil];
  [_progress stop];
}

- (void) go:(void(^)(void))over {
  if (!_playing) {
    _index = 0;
    return;
  }
  if (_index == ([_waves count] - 1)) {
    _index = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
      over();
    });
    return;
  }
  [((WaveLayer *)_waves[_index]) push];
  _index++;
  [self performSelector:@selector(go:)
             withObject:over
             afterDelay:0.5F];
}

- (void)dealloc {
  [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

- (CAShapeLayer *)shapeWithRadius:(CGFloat)radius frame:(CGRect)frame fillColor:(UIColor *)color {
  UIBezierPath *path = [UIBezierPath bezierPath];
  [path addArcWithCenter:CGPointMake(WAVE_RADIUS, WAVE_RADIUS)
                  radius:radius
              startAngle:0
                endAngle:2 * M_PI
               clockwise:NO];
  CAShapeLayer *shape = [CAShapeLayer layer];
  shape.fillColor = [color CGColor];
  shape.frame = frame;
  shape.path = [path CGPath];
  return shape;
}

@end
